<?php
namespace app\common\model;

use org\util\FileUtil;
use think\Db;
use think\helper\Str;

class CmsMoudleModel extends BaseModel
{

    protected $name = 'cms_moudle'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    /*读取器*/
    protected function getIsSystemTextAttr($value, $data)
    {
        $status = [
            0 => '<span class="label label-warning">普通模型</span>',
            1 => '<span class="label label-success">系统模型</span>',
        ];
        return $status[$data['is_system']];
    }

    protected function getValidateTplTextAttr($value, $data)
    {
        $status = [
            0 => '<span class="label label-warning">未生成</span>',
            1 => '<span class="label label-primary">已生成</span>',
            2 => '<span class="label label-success">已锁定</span>',
        ];
        return $status[$data['validate_tpl']];
    }

    protected function getModelTplTextAttr($value, $data)
    {
        $status = [
            0 => '<span class="label label-warning">未生成</span>',
            1 => '<span class="label label-primary">已生成</span>',
            2 => '<span class="label label-success">已锁定</span>',
        ];
        return $status[$data['model_tpl']];
    }

    protected function getEnableTextAttr($value, $data)
    {
        $status = [
            0 => '<span class="label label-warning">关闭</span>',
            1 => '<span class="label label-success">开启</span>',
        ];
        return $status[$data['enable']];
    }
    /*修改器*/

    /**
     * 更新模型缓存
     */
    public function updateCache()
    {
        $moudle      = obj2array($this->select());
        $cache       = [];
        $fieldMoudle = new CmsFieldModel();
        foreach ($moudle as $m) {
            $fieldMoudle->updateCache($m['mid']);
            $fieldMoudle->flagCache($m['mid']);
            $cache[$m['mid']] = $m;
        }
        cache('cms_moudle', $cache);
        return true;
    }

    /**
     * 添加模型
     * @param $data
     */
    public function addData($data)
    {
        if ($this->getByTableName($data['table_name'])) {
            $this->error = '模型表名已存在！';
            return false;
        }
        $this->isUpdate(false)->allowField(true)->save($data); //添加模型记录
        $table_name = $data['table_name']; //获取表名
        if ($this->createMoudleSql($table_name)) {
            $this->FieldInit($this->getAttr('mid'), $table_name);
            return true;
        } else {
            $this->error = $this->getError();
            return false;
        }
    }

    /**
     * 删除模型
     */
    public function delData($mid)
    {
        //验证栏目信息
        if (Db::table('cms_category')->where('mid', $mid)->find()) {
            $this->error = '请先删除模型栏目!';
            return false;
        }
        $tableName = Db::table('cms_moudle')->where('mid', $mid)->value('table_name');
        //开启事务
        Db::startTrans();
        try {
            //删除主表
            Db::execute('DROP TABLE IF EXISTS `' . config('database.prefix') . $tableName . '`');
            //删除副表
            Db::execute('DROP TABLE IF EXISTS `' . config('database.prefix') . $tableName . '_data`');
            //删除表记录
            Db::table('cms_moudle')->where('mid', $mid)->delete();
            //删除字段记录
            Db::table('cms_field')->where('mid', $mid)->delete();
            Db::commit(); // 提交事务
            //删除对应文件
            FileUtil::unlinkFile(APP_PATH . '/common/model/' . Str::studly($tableName) . 'Model.php');
            FileUtil::unlinkFile(APP_PATH . '/common/validate/' . Str::studly($tableName) . 'Validate.php');
            return true;
        } catch (Exception $e) {
            Db::rollback(); // 回滚事务
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 创建模型表
     */
    public function createMoudleSql($tableName)
    {
        $zhubiaoSql = file_get_contents(APP_PATH . 'system/sql/cms_moudle.sql');
        $fuBiaoSql  = file_get_contents(APP_PATH . 'system/sql/cms_moudle_data.sql');
        $zhubiaoSql = preg_replace(
            ['/@pre@/', '/@table@/'], [config('database.prefix'), $tableName],
            $zhubiaoSql
        );
        $fuBiaoSql  = preg_replace(
            ['/@pre@/', '/@table@/'], [config('database.prefix'), $tableName],
            $fuBiaoSql
        );
        // 启动事务
        Db::startTrans();
        try {
            Db::execute($zhubiaoSql); //创建主表
            Db::execute($fuBiaoSql); //创建附表
            Db::commit(); // 提交事务
            return true;
        } catch (\Exception $e) {
            Db::rollback(); // 回滚事务
            $this->error = $e->getMessage();
            return false;
        }
    }

    //字段初始化
    private function FieldInit($mid, $tableName)
    {
        $dataList = [
            [
                'mid'            => $mid,
                'table_name'     => $tableName,
                'table_type'     => 1,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '标题',
                'field_name'     => 'title',
                'field_type'     => 'input',
                'field_sort'     => 1,
                'set'            => '{"layout":"1","size":"10","length":"255","default":""}',
                'validate'       => '["require"]',
                'tips'           => '请输入内容标题',
                'validate_scene' => 3,
            ], [
                'mid'            => $mid,
                'table_name'     => $tableName,
                'table_type'     => 1,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '栏目',
                'field_name'     => 'cid',
                'field_type'     => 'cid',
                'field_sort'     => 2,
                'set'            => '{"layout":"1","size":"4"}',
                'validate'       => '["require"]',
                'tips'           => '',
                'validate_scene' => 3,
            ], [
                'mid'            => $mid,
                'table_name'     => $tableName,
                'table_type'     => 1,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '缩略图',
                'field_name'     => 'thumb',
                'field_type'     => 'image',
                'field_sort'     => 3,
                'set'            => '{"layout":"1","size":"4","length":"255","default":""}',
                'validate'       => '',
                'tips'           => '',
                'validate_scene' => 0,
            ], [
                'mid'            => $mid,
                'table_name'     => $tableName,
                'table_type'     => 1,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '属性',
                'field_name'     => 'flag',
                'field_type'     => 'flag',
                'field_sort'     => 4,
                'set'            => '{"layout":"1","size":"10"}',
                'validate'       => '',
                'tips'           => '',
                'validate_scene' => 0,
            ], [
                'mid'            => $mid,
                'table_name'     => $tableName,
                'table_type'     => 1,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '转向链接',
                'field_name'     => 'redirecturl',
                'field_type'     => 'input',
                'field_sort'     => 5,
                'set'            => '{"layout":"1","size":"10","length":"255","default":""}',
                'validate'       => '',
                'tips'           => '',
                'validate_scene' => 0,
            ], [
                'mid'            => $mid,
                'table_name'     => $tableName,
                'table_type'     => 1,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '关键词',
                'field_name'     => 'keywords',
                'field_type'     => 'input',
                'field_sort'     => 6,
                'set'            => '{"layout":"1","size":"10","length":"100","default":""}',
                'validate'       => '',
                'tips'           => '',
                'validate_scene' => 0,
            ], [
                'mid'            => $mid,
                'table_name'     => $tableName,
                'table_type'     => 1,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '描述',
                'field_name'     => 'description',
                'field_type'     => 'textarea',
                'field_sort'     => 7,
                'set'            => '{"layout":"1","size":"10","length":"255","default":""}',
                'validate'       => '',
                'tips'           => '',
                'validate_scene' => 0,
            ], [
                'mid'            => $mid,
                'table_name'     => $tableName . '_data',
                'table_type'     => 2,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '内容',
                'field_name'     => 'content',
                'field_type'     => 'editor',
                'field_sort'     => 8,
                'set'            => '{"layout":"1","size":"10","default":""}',
                'validate'       => '',
                'tips'           => '',
                'validate_scene' => 0,
            ], [
                'mid'            => $mid,
                'table_name'     => $tableName,
                'table_type'     => 1,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '排序',
                'field_name'     => 'sort',
                'field_type'     => 'input',
                'field_sort'     => 9,
                'set'            => '{"layout":"2","size":"4","field_type":"smallint","num_integer":"4","num_decimal":"0","default":"0"}',
                'validate'       => '["number"]',
                'tips'           => '',
                'validate_scene' => 3,
            ], [
                'mid'            => $mid,
                'table_name'     => $tableName,
                'table_type'     => 1,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '模板',
                'field_name'     => 'content_tpl',
                'field_type'     => 'tpl',
                'field_sort'     => 10,
                'set'            => '{"layout":"2","size":"4","length":"50","default":""}',
                'validate'       => '["require"]',
                'tips'           => '非专业人员请勿修改',
                'validate_scene' => 3,
            ], [
                'mid'            => $mid,
                'table_name'     => $tableName,
                'table_type'     => 1,
                'enable'         => 1,
                'is_system'      => 1,
                'title'          => '状态',
                'field_name'     => 'status',
                'field_type'     => 'box',
                'field_sort'     => 11,
                'set'            => '{"layout":"1","size":"10","form_type":"radio","field_type":"smallint","options":"0|待审,1|发表","length":"1","default":"1"}',
                'validate'       => '["number"]',
                'tips'           => '',
                'validate_scene' => 3,
            ],
        ];
        return Db::table('cms_field')->insertAll($dataList);
    }

    /**
     * 获取待生成文件列表
     * @param $moudleInfo
     * @return array
     */
    public function getBuildList($moudleInfo)
    {
        $filename  = Str::studly($moudleInfo['table_name']);
        $buildList = [
            'validate' => [
                'name'       => '验证器页面',
                'file'       => 'app/common/validate/' . $filename . 'Validate.php',
                'status_tpl' => $moudleInfo->validate_tpl_text,
                'tpl_field'  => 'validate_tpl',
                'tpl_value'  => $moudleInfo->validate_tpl,
                'build_url'  => url('CmsBuildMoudle/buildValidate', ['mid' => $moudleInfo->mid]),
            ],
            'model'    => [
                'name'       => '模型页面',
                'file'       => 'app/common/model/' . $filename . 'Model.php',
                'status_tpl' => $moudleInfo->model_tpl_text,
                'tpl_field'  => 'model_tpl',
                'tpl_value'  => $moudleInfo->model_tpl,
                'build_url'  => url('CmsBuildMoudle/buildModel', ['mid' => $moudleInfo->mid]),
            ],
        ];
        return $buildList;
    }
}